<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Home\DouyinListController;
use App\Models\PartnerModels\Photo;
use App\Models\UserModels\User;
use App\Models\PartnerModels\Partner;
use App\Models\PartnerModels\VideoComment;
use Illuminate\Http\Request;
use App\Models\DyModels\ReceiveMsg;
use DB;
use App\Models\PartnerModels\ApiUser;
use App\Models\ExpModels\ExpCard;
use App\Components\Tools;
use App\Models\UserModels\UserConsulting;
use App\Models\ExpModels\Exp;
use App\Components\CodeTools;
class ApiUserController extends Controller
{
    /**
     *    移动端事件消息
     */

    public function __construct(Request $request)
    {
//        $this->url = Tools::getOneconfig("/config/third.json", array('qiniu', 'qnUrl'));
        $this->params = $request->all();
    }
    public function testapp(){
        $body = $_POST;//获取提交过来的数据
       // $data = json_decode($body, true); //对获取的数据进行解析
        print_r($body);exit();
    }


    //生成token
    public function getToken(){
        $base = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $count = strlen($base);
        $random = '';
        for ($i=0; $i < 16; $i++) {
         $random.=$base[mt_rand(0,$count-1)];
        }
        return md5($random);
    }


    public function mobileLogin(Request $request)
    {
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        //第一次登录的
        $uip = $request->getClientIp();//获取调用接口的用户的ip
       // print_r($body);exit();
        $soApiUser = new ApiUser();
        //获取数据库的对应用户ip
//        $userip=$soApiUser->checkuip($data['user']);
        if (isset($data['user']) && isset($data['type']) && isset($data['pwd'])) {
          //  print_r(111);
            $pwd = \App\Components\Tools::passwordEncryption(trim($data['pwd']));
            $time = date('Y-m-d', time());
            //判断用户对应的账号名是不是有ip一类的 为空就存档登录 有的话对比登录 登录完之后存token
            $re = $soApiUser->checkApiUname($data['user'],$pwd,$time,$data['type']);
            if ($re) {//账号密码都对的情况下进行二次判断
                if (isset($re['equipment_id']) && !empty($re['equipment_id']) && isset($re['mac']) && !empty($re['mac']) && isset($re['type'])) {//设备id存在的话

                    if ($re['equipment_id'] == $data['equipment_id'] && $re['mac'] == $data['mac'] && $data['type']==$re['type'] ) {//设备id相同
                        //设备一致可以登录

                        $tkey = $this->getToken();
                        $soApiUser->saveTaocan(['api_token'=>$tkey], $re['id']);
                        $result = [
                            "code" => 1,
                            "uid" => $re['id'],
                            "token" =>$tkey,
                            "msg" => '登录成功',
                        ];
                        return response()->json($result);
                    } else {
                        //设备不一致
                        $result = [
                            "code" => 0,
                            "msg" => '请使用原设备登录',
                        ];
                        return response()->json($result);
                    }
                } else {//账号密码以及状态时间都符合 没有设备id 所以更新数据库

                    $this->firstLogin($data, $re['id'], $uip);
                    $tkey = $this->getToken();
                    $soApiUser->saveTaocan(['api_token'=>$tkey], $re['id']);
                    $result = [
                        "code" => 1,
                        "uid" => $re['id'],
                        "token" =>$tkey,
                        "msg" => '登录成功',
                    ];
                    return response()->json($result);
                }
            } else {
                $result = [
                    "code" => 0,
                    "msg" => '账号密码错误',
                ];
                return response()->json($result);
            }
        }
    }

    //请求查看卡卷的方法
    public function cardinfo()
    {
        //  print_r(1111);exit();
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        //第一次登录的
        $soExpCard = new ExpCard();
        //   return 2222;
        if ($data['pid']) {
            //   return  1111;
            $time = date('Y-m-d H:i:s', time());//接口接收时间
            $res = $soExpCard->getCardInfo($data['pid'] );

            if ($res) {//如果存在数据
                $result = [
                    "code" => 1,
                    "msg" => '查询成功',
                    "data" => $res,
                ];
                return response()->json($result);//响应返回json形式的数据
            }
        }else{
            $result = [
                "code" => 0,
                "msg" => '服务器暂无响应',
            ];
            return response()->json($result);//响应返回json形式的数据
        }

    }
    //查看活动数据数据的方法
    public function activeInfo(){
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        if(!empty($data['actid']) && !empty($data['uid'])){//判断是否存在空值 catid 活动id uid 用户id
            //获取对应的用户数据
            $soExpcard=new ExpCard();
            $res=$soExpcard->getAllInfo($data['actid']);
            $result = [
                "code" => 1,
                "msg" => '请求成功',
                'data'=>$res,
            ];
            return response()->json($result);//响应返回json形式的数据
        }else{
            $result = [
                "code" => 0,
                "msg" => '参数错误',
            ];
            return response()->json($result);//响应返回json形式的数据
        }
    }
    //第一次登录更新数据库的方法
    public function firstLogin($data, $id, $uip)
    {
        $soApiUser = new ApiUser();
        $date = array(
            'type' => $data['type'],
            'ip' => $uip,
            'equipment_id' => $data['equipment_id'],
            'mac' => $data['mac'],
            'update_time' => date('Y-m-d H:i:s', time()),
        );
        $soApiUser->saveTaocan($date, $id);
    }


    //查询access_token的方法
    public function getaccesstoken($open_id)
    {
        $sql = " select access_token from pt_dy_access_token where open_id='$open_id' ";
        $token = DB::select($sql);
        return $token;
    }

    //根据openid以及备用信息spare和回复类型reply_type查询出对应的关键字和回复词
    public function getAllInfo($openid, $reply_type)
    {
        $sql = "select search_word,reply_word,open_id from pt_keyword_automatic where open_id='$openid' and spare=1 and reply_type=$reply_type";
        $openid = DB::select($sql);
        return $openid;
    }
    //官网客户填写表单的处理方法
    public function consultinginfo(){
        $soUserConsulting= new UserConsulting();
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        //进行数据判断
        $time = date('Y-m-d H:i:s', time());//接口接收时间
        if(!empty($data['user']) && !empty($data['mobile'])){
            $checkUmobile=\App\Components\Tools::checkUmobile($data['mobile']);
         if(!$checkUmobile){
             $result = [
                 "code" => 0,
                 "xcx_type" => 0,
                 "msg" => '请输入正确的信息',
             ];
             return response()->json($result);
         }else{
             $result = [
                 "code" => 1,
                 "xcx_type" => 0,
                 "msg" => '填写完成，后续我们这边会有客服人员联系你们',
             ];
             $date=array(
                 'user' => $data['user'],
                 'type' => $data['type'],
                 'mobile' => $data['mobile'],
                 'status' => 0,
                 'create_time' =>$time,
                 'update_time' => date('Y-m-d H:i:s', time()),
                 'comment' => isset($data['comment']) ? $data['comment'] : '',
             );
             DB::table("pt_user_consulting")->insertGetId($date);//把榜单视频数据按昵称存入库
             return response()->json($result);
         }
        }else{
            $result = [
                "code" => 0,
                "xcx_type" => 0,
                "msg" => '请输入正确的信息',
            ];
            return response()->json($result);
        }
    }
    //获取商家联系方式
    function getInformation(){
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        $soUserConsulting= new UserConsulting();//这暂时替代的 实际上是要的商家的数据库表
        if(!empty($data['id'] ) && !empty($data['type'])){//如果传来的值不为空
            //查询对应的账号手机微信号
            $res=$soUserConsulting->getGwInfo($data['id'],$data['type']);
            if(!$res){//如果数据不存在
                $result = [
                    "code" => 0,
                    "xcx_type" => 0,
                    "msg" => '参数错误',
                ];
                return response()->json($result);
            }else{
                $result = [
                    "code" => 1,
                    "xcx_type" => 0,
                    "msg" => '请求成功',
                    'mobile'=>isset($res[0]['mobile']) ? $res[0]['mobile']:'',
                    'weixin'=>isset($res[0]['wechat']) ? $res[0]['wechat']:'',
                ];
                return response()->json($result);
            }
        }else{
            $result = [
                "code" => 0,
                "xcx_type" => 0,
                "msg" => '参数错误',
            ];
            return response()->json($result);
        }
    }
    function getGwInformation(){
        $soUserConsulting= new UserConsulting();//这暂时替代的 实际上是要的商家的数据库表
        $res=$soUserConsulting->getGwInfo();
        if(!$res){//如果数据不存在
            $result = [
                "code" => 0,
                "xcx_type" => 0,
                "msg" => '参数错误',
            ];
            return response()->json($result);
        }else{
            $result = [
                "code" => 1,
                "xcx_type" => 0,
                "msg" => '请求成功',
                'mobile'=>isset($res[0]['mobile']) ? $res[0]['mobile']:'',
                'weixin'=>isset($res[0]['wechat']) ? $res[0]['wechat']:'',
            ];
            return response()->json($result);
        }
    }
    //获取移动端首页数据 需要传id  达人/广告/直播 暂无数据
    function  getHomeInfo(){
        //   print_r(1111);
        $code = new CodeTools();
        $soPhoto=new Photo();
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        //开启判断
        if(!empty($data['id'])){
            $photo=$soPhoto->getAllInfo();//获取首页轮播图数据
            //获取tips
            $tips=$soPhoto->getTips();
            //获取当日获客数量
            $videocount=$soPhoto->getxunpancount($data['id']);
            //获取当日私信的数量（已私信处理数量）
            $videosxcount=$soPhoto->getkeyWordCount($data['id']);
            //获取视频（视频雷达/广告雷达）的获客数量
            $spldcount=$soPhoto->getVideoCount($data['id'],2);
            //获取视频获客的私信处理数量
            $spsxcount=$soPhoto->getVideoSxCount($data['id'],2);
            //获取视频广告雷达的获客数量
            $ggldcount=$soPhoto->getVideoCount($data['id'],3);
            //获取广告雷达的私信处理数量
            $ggsxcount=$soPhoto->getVideoSxCount($data['id'],3);
            //获取达人（账户雷达）获客数量
            $drldcount=$soPhoto->getDrCount($data['id'],1);
            //获取达人（账户雷达）私信数量
            $drsxcount=$soPhoto->getDrSxCount($data['id'],1);
           // print_r($ggsxcount);exit();
            $date=array(
                'photo'=>$photo,
                'tips'=>$tips,
                'videocount'=>$videocount,
                'videosxcount'=>$videosxcount,
                'spldcount'=>$spldcount,
                'spsxcount'=>$spsxcount,
                'ggldcount'=>$ggldcount,
                'ggsxcount'=>$ggsxcount,
                'drldcount'=>$drldcount,
                'drsxcount'=>$drsxcount,
            );
            return $code->apiRturn(1, $date);
        }else{
            return $code->apiRturn(0);
        }

    }
    //接口获取指定时间段的数据
    public function getCommentInfo(){
        $code = new CodeTools();
        $soPhoto=new Photo();
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        if(!empty($data['id'])){
            $keywordcount=$soPhoto->getKeywordCenter($data['id']);
            $videocount=$soPhoto->getVideoCenter($data['id'],2);
            $ggcount=$soPhoto->getVideoCenter($data['id'],3);
            $drcount=$soPhoto->getdrCenter($data['id'],1);
            $date=array(
                'keywordcount'=>$keywordcount,
                'videocount'=>$videocount,
                'ggcount'=>$ggcount,
                'drcount'=>$drcount,
            );
            return $code->apiRturn(1, $date);
            //获取关键词雷达客户（当日/7日/30日/总数据）、

            //获取关键词雷达私信数据（当日/7日/30日/总数据）、
        }else{
            return $code->apiRturn(0);
        }

    }
    // 接口 获取我的页面的相关
    public function getSelfInfo(){
        $code = new CodeTools();
        $soPartner=new Partner();
        $soVideoComment=new VideoComment();
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        if (!empty($data['id'])){ //目前判断id,type(会员还是合伙人) 所有数据更加id查询
            $info=$soPartner->getSelfInfo($data['id']);
            //获取总获客条数
            $allXunpanCount=$soVideoComment->getXunPan($data['id']);
            $data=array(
                'userinfo'=>$info,
                'allXunpanCount'=>$allXunpanCount,
            );
            return $code->apiRturn(1, $data);
        }else{
            return $code->apiRturn(0);
        }
    }
//接口 修改密码
public function editPassWord(){
    $code = new CodeTools();
    $soPartner=new Partner();
    $soVideoComment=new VideoComment();
    $body = file_get_contents("php://input");//获取提交过来的数据
    $data = json_decode($body, true); //对获取的数据进行解析
   // print_r($data);exit();
    if(!empty($data['id']) && !empty($data['newpwd']) && !empty($data['oldpwd'])){//判断存在id new pwd  旧密码oldpwd
        //检查是否存在对应的id账号
        $checkpwd=$soPartner->validAdminLogin($data['id'],$data['oldpwd'],$data['type']);
        if(!empty($checkpwd)){//验证通过
            //设置新密码
           if($soPartner->db_update('', $data['id'], ['pwd' => \App\Components\Tools::passwordEncryption($data['newpwd'])])){
               return $code->apiRturn(1);//成功回调
           } else{
               return $code->apiRturn(0); //失败回调
           }
        }else{
            return $code->apiRturn(0);//验证失败回调
        }
    }else{
        return $code->apiRturn(0);//传递参数错误回调
    }
}
    //我的页面 高级功能
    public function editGjRoul(){
        $code = new CodeTools();
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        if(!empty($data['id']) ){//如果id为空 返回错误
            if(!empty($data['roul'])){//如果手机权限修改存在
                //修改对应表
                return $code->apiRturn(1);
            } elseif(!empty($data['zhibo'])){
                //修改对应表字段
                return $code->apiRturn(1);
            }elseif(!empty($data['auto'])){
                //修改对应表字段
                return $code->apiRturn(1);
            }else{
                //传了id但是没存字段 返回数据错误
                return $code->apiRturn(0);
            }
        }else{//不存在id
            return $code->apiRturn(0);//传递参数错误回调
        }
    }
    //重置密码的接口
    public function resetPwd(){
        $code = new CodeTools();
        $soPartner=new Partner();
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        if(!empty($data['id']) && !empty($data['newpwd'])){
            if($soPartner->db_update('', $data['id'], ['pwd' => \App\Components\Tools::passwordEncryption($data['newpwd'])])){
                return $code->apiRturn(1);
            }
        }else{
            return $code->apiRturn(0);
        }
    }
    //请求接口获取直播间数据并且入库的方法
    function getLiveInfo(){
        //获取所有的需要更新的直播间号码
    //    $solive=new
       // $sql="";
        $date=111;
        // 循环请求接口获取数据、$url 请求的链接  id从上面获取
        //数据整理好
        //数据入库
    }
}